import ajax from '@/utils/sysAjax'
import type * as sysCommonModel from '@/api/model/sysCommonModel'
import type { CustomResponse } from 'uni-ajax'
import { platform } from '@/utils/platform'
import useUserStore from '@/store/user'
import moment from 'moment'
import env from '@/config/env'

class SysCommonService {
  /**
   * 上传
   */
  upload({
    filePath,
    formData = {},
    name = 'file',
    uploadTaskCallback,
  }: sysCommonModel.IUploadParams): Promise<CustomResponse<Array<string>>> {
    const userStore = useUserStore()
    const biz = `dy-${env.uploadBiz}/${
      userStore.userInfo?.username
    }/${moment().format('YYYY-M-D')}`
    return new Promise((resolve, reject) => {
      const uploadTask = uni.uploadFile({
        url: `${env.baseUrl}sys/common/upload`,
        filePath,
        formData: {
          biz,
          ...formData,
        },
        name,
        header: {
          'User-Port': platform,
          'X-Access-Token': userStore.token,
          "Authorization": "Bearer " + userStore.token,
          'X-Tenant-Id' : '1000',
        },
        success: res => {
          try {
            const data = JSON.parse(res.data)
            if (data.success) {
              resolve({
                code: 200,
                message: '上传成功',
                result: data.message.split('||'),
                success: true,
              })
            } else {
              reject({
                code: 500,
                message: '上传失败',
                result: null,
                success: false,
              })
            }
          } catch (e) {
            reject({
              code: 500,
              message: e,
              result: null,
              success: false,
            })
          }
        },
      })
      uploadTaskCallback?.(uploadTask)
    })
  }

  /**
   * 下载
   */
  async downLoad(urls: Array<string>) {
    // const settingStore = useSettingStore()
    // const writePhotosAlbumRes = await settingStore.getScope(
    //   EnumScope.WritePhotosAlbum
    // )
    // if (!writePhotosAlbumRes) return Promise.reject(false)

    // 下载保存图片
    const downAndSave = (url: string): Promise<boolean> =>
      new Promise((resolve, reject) => {
        uni.downloadFile({
          url,
          success: res => {
            uni.saveImageToPhotosAlbum({
              filePath: res.tempFilePath,
              success: () => resolve(true),
              fail: () => reject(false),
            })
          },
          fail: () => reject(false),
        })
      })

    const downLoadTask = urls.reduce(
      (pre: Array<Promise<boolean>>, cur) => [...pre, downAndSave(cur)],
      []
    )

    return Promise.all(downLoadTask)
  }

  /**
   * 批量删除
   */
  deleteByUrl(
    params: sysCommonModel.IDeleteByUrlParams
  ): Promise<CustomResponse<null>> {
    return ajax.post('/sys/common/deleteByUrl', params)
  }
}

export default new SysCommonService()
